﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace ProcessManager
{
    public partial class Form1 : Form
    {
        private ProcessInfo pInfo = new ProcessInfo();
        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            pInfo.mDict = new Dictionary<int, MyProcess>();
            //Process[] allPros = Process.GetProcessesByName("qq");
            //foreach (var p in allPros)
            //{
            //    MyProcess mPro = new MyProcess();
            //    mPro.Active = true;
            //    mPro.ProceID = p.Id;
            //    mPro.ProceName = p.ProcessName;

            //    pInfo.mDict.Add(p.Id, mPro);
            //}

            //timer1.Interval = 1000;
            //timer1.Start();

            //PerformanceCounter p = new PerformanceCounter();
            //Process[] prArgs = Process.GetProcessesByName("onjitRelease3");
            //if (prArgs != null && prArgs.Length > 0)
            //{
            //    foreach (Process pr in prArgs)
            //    {
            //        textBox1.Text += string.Format("{0}:{1}  {2}\r\n", pr.Id, pr.TotalProcessorTime.TotalMilliseconds, pr.PeakWorkingSet);
            //    }
            //}
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                SearchWindow();
            }
            catch { }
        }

        //#region CPUUsage

        ///// <summary>
        ///// 性能计数器，用于获取CPU空闲百分比
        ///// </summary>
        //private static PerformanceCounter mIdle = new PerformanceCounter("Process", "% Processor Time", "Idle");
        ///// <summary>
        ///// 性能计数器，用于获取CPU总利用率
        ///// </summary>
        //private static PerformanceCounter mTotal = new PerformanceCounter("Process", "% Processor Time", "_Total");
        //private double mCurrentTotalCpuTime;
        //private double mIdleCpuPercent;

        //private void FillNeedRefreshInfo(params Process[] pCurrentAll)
        //{
        //    //以下计算CPU利用率
        //    this.mCurrentTotalCpuTime = this.CalCurrentTotalCpuTime();
        //    for (int i = 0; i < pCurrentAll.Length; i++)
        //    {
        //        //空闲进程idle
        //        if (pCurrentAll[i].Id == 0)
        //        {
        //            this.mDict[pCurrentAll[i].Id].CpuPercent = this.mIdleCpuPercent;
        //        }
        //        else
        //        {
        //            try
        //            {
        //                //无法保证进程不会中途退出，此时无法获取其Cpu时间
        //                long ms = (long)pCurrentAll[i].TotalProcessorTime.TotalMilliseconds;
        //                double d = (ms - this.mDict[pCurrentAll[i].Id].OldCpuTime) * 1.0 / this.mCurrentTotalCpuTime;
        //                this.mDict[pCurrentAll[i].Id].CpuPercent = d;
        //                this.mDict[pCurrentAll[i].Id].OldCpuTime = ms;
        //            }
        //            catch
        //            {
        //            }
        //        }

        //        //调用刷新事件
        //        if (this.HandleProceRefresh != null)
        //        {
        //            this.HandleProceRefresh(this.mDict[pCurrentAll[i].Id], 100 - this.mIdleCpuPercent);
        //        }
        //    }
        //}


        //private double CalCurrentTotalCpuTime()
        //{
        //    double d = 0;
        //    //获取性能计数器值
        //    double idlePercent = mIdle.NextValue();
        //    double totalPercent = mTotal.NextValue();
        //    //避免除0异常
        //    if (totalPercent == 0)
        //    {
        //        this.mIdleCpuPercent = 0;
        //    }
        //    else
        //    {
        //        //可能遇到多核或超线程CPU，CPU空闲进程比率不能直接使用计数器的值
        //        this.mIdleCpuPercent = idlePercent * 100 / totalPercent;
        //    }

        //    //以下获取上一次计算至当前总的非空闲CPU时间
        //    foreach (Process p in this.mCurrentAll)
        //    {
        //        //对空闲进程及中途退出的进程不做处理
        //        if (p.Id == 0 || p.HasExited)
        //        {
        //            continue;
        //        }

        //        if (this.mDict ==null || !this.mDict.ContainsKey(p.Id))
        //        {
        //            d += p.TotalProcessorTime.TotalMilliseconds;
        //        }
        //        else
        //        {
        //            d += p.TotalProcessorTime.TotalMilliseconds - this.mDict[p.Id].OldCpuTime;
        //        }
        //    }

        //    //当前非空闲CPU时间/当前非空闲时间所占比率=当前总CPU时间
        //    //return d / (totalPercent - idlePercent);
        //    return d / (100 - mIdleCpuPercent);
        //}

        //#endregion

        //方法声明
        [DllImport("user32.dll")]
        static extern int SendMessage(IntPtr Handle, int WParam, int LParam);

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);

        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
        private static extern void SetForegroundWindow(IntPtr hwnd);

        [DllImport("user32.dll", EntryPoint = "PostMessage")]
        private static extern int PostMessage(int hWnd, int msg, int wParam, uint lParam);

        [DllImport("User32.dll", EntryPoint = "ShowWindow")]
        private static extern bool ShowWindow(int hWnd, int nCmdShow);

        const int WM_GETTEXT = 0x000D;
        const int WM_SETTEXT = 0x000C;
        const int WM_CLICK = 0x00F5;
        /// <summary>
        /// 激活并显示一个窗口。
        /// 如果窗口被最小化或最大化，系统将其恢复到原来的尺寸和大小。
        /// 应用程序在第一次显示窗口的时候应该指定此标志
        /// </summary>
        const int SW_SHOWNOMAL = 1;

        private int SearchWindow()
        {
            int retval = 0; //增加一个返回值用来判断操作是否成功 

            //下面的这些参数都可以用Spy++查到 
            string lpszParentClass = "WindowsForms10.Window.8.app.0.2bf8098_r12_ad1"; //整个窗口的类名 
            string lpszParentWindow = "倚天2-国际脱机辅助"; //窗口标题 
            string lpszClass = "menuStrip1"; //需要查找的子窗口的类名，也就是用户名输入框 
            string lppassword = "ATL:30A4D1D8";//密码输入框
            string lpszClass_Submit = "StandardButton"; //需要查找的Button的类名 

            IntPtr ParenthWnd = new IntPtr(0);
            IntPtr EdithWnd = new IntPtr(0);

            //查到窗体，得到整个窗体 
            ParenthWnd = FindWindow(lpszParentClass, lpszParentWindow);

            //判断这个窗体是否有效 
            if (!ParenthWnd.Equals(IntPtr.Zero))
            {
                ShowWindow(ParenthWnd.ToInt32(), SW_SHOWNOMAL);
                SetForegroundWindow(ParenthWnd);
                Thread.Sleep(2000);
                //得到User Name这个子窗体，并设置其内容 
                EdithWnd = FindWindowEx(ParenthWnd, EdithWnd, lpszClass, "");
                if (!EdithWnd.Equals(IntPtr.Zero))
                {

                    //调用SendMessage方法设置其内容 
                    SendMessage(EdithWnd, WM_SETTEXT, (IntPtr)0, "bbbbbb");
                    retval++;
                }
                //得到Password这个子窗体，并设置其内容 

                EdithWnd = FindWindowEx(ParenthWnd, EdithWnd, lppassword, "");
                if (!EdithWnd.Equals(IntPtr.Zero))
                {

                    SendMessage(EdithWnd, WM_SETTEXT, (IntPtr)0, "aaaaaaaaa");
                    retval++;
                }

                //得到Button这个子窗体，并触发它的Click事件 
                //EdithWnd = FindWindowEx(ParenthWnd, EdithWnd, lpszClass_Submit, lpszName_Submit);
                //if (!EdithWnd.Equals(IntPtr.Zero))
                //{
                //    SendMessage(EdithWnd, WM_CLICK, (IntPtr)0, "0");
                //    retval++;
                //}
            }

            return retval;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            textBox1.Text = string.Empty;
            pInfo.RefreshProceList(true);
            Thread.Sleep(100);
            foreach (var p in pInfo.mDict)
            {
                textBox1.Text += string.Format("{0}%", p.Value.CpuPercent);
            }
        }
    }
}
